package pers.smalltown.authorize.wechat;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.client.RestTemplate;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JsonMappingException;

import pers.smalltown.authorize.consts.Consts;
import pers.smalltown.authorize.consts.OurSpaceUri;
import pers.smalltown.authorize.consts.SSmellService;
import pers.smalltown.authorize.wechat.dto.WxAccessToken;

import javax.ws.rs.PathParam;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@CrossOrigin(origins = "*")
@RestController
@RequestMapping("/wechat")
public class WechatOAuth {
    @Autowired
    DiscoveryClient discoveryClient;
    @Autowired
    WechatUtils wechatUtils;
    
    @GetMapping("/callback")
    public String callback() {
        System.out.println("CallBack:" + SSmellService.OURSPACE);
        List<ServiceInstance> services = discoveryClient.getInstances(SSmellService.OURSPACE.name());
        services.forEach((ServiceInstance instanceInfo) -> {
           System.out.println("instanceInfo: " + instanceInfo);
        });
        String serviceUri = String.format("%s%s", services.get(0).getUri(), OurSpaceUri.getWantdo());

        RestTemplate restTemplate = new RestTemplate();
//        ResponseEntity<String> result = restTemplate.exchange(serviceUri, HttpMethod.GET, null, String.class);
        Map<String, String> result = restTemplate.getForObject(serviceUri, Map.class);
        System.out.format("result:%s\n", result);
        return "Wechat callback";
    }

    @Autowired
    RestTemplate restTemplate;
    @GetMapping("/ribbon/callback")
    public Object ribbonCallback() {
        System.out.println("ribbonCallback");
        Map<String,String> result = restTemplate.getForObject(
                String.format("http://%s%s", SSmellService.OURSPACE.getName(), OurSpaceUri.getWantdo()),
                Map.class
        );
        return result;
    }

    @GetMapping("/access")
    public Map<String, Object> doAccess(@RequestParam("authCode") String authCode) throws JsonMappingException, JsonProcessingException {
        System.out.println("Auth code:" + authCode);
        Map<String, Object> resultMap = new HashMap<>();
        WxAccessToken result = wechatUtils.getOpenId(authCode);
        String openId = result.getOpenid();
        if (openId == null) {
        	resultMap.put("errmsg", "not get openId, " + result.getErrmsg());
        } else {
        	resultMap.put("openid", result.getOpenid());
        }
        System.out.println("doAccess return:" + resultMap);
        return resultMap;
    }
}
